import {getValueFromUrl} from "./utils.js"

function getUserInfo(uid) {
    $.ajax({
        url: "http://www.woniu-news.com:8082/getUserDetailById.php",
        type: "GET",
        xhrFields: {
            withCredentials: true
        },
        data: {
            uid
        },
        dataType: "json",
        success: (resp) => {
            if (resp.code === 200) {
                $("#username").val(resp.data.username)
                $("#email").val(resp.data.mail)
                $("#role").val(resp.data.role)
                $("#status").val(resp.data.status)
            } else if (resp.code === 401) {
                alert(resp.message)
                window.location.href = "index.html"
            } else {
                alert(resp.message)
            }
        },
        error: (resp) => {
            alert(resp.message)
        }
    })
}

function editUser(uid) {
    const username = $("#username").val()
    const mail = $("#email").val()
    const role = $("#role").val()
    const status = $("#status").val()

    $.ajax({
        url: "http://www.woniu-news.com:8082/editUserById.php",
        type: "POST",
        xhrFields: {
            withCredentials: true
        },
        data: {
            uid,
            username,
            mail,
            role,
            status
        },
        dataType: "json",
        success: (resp) => {
            if (resp.code === 200) {
                alert(resp.message)
                window.location.href = "user_management.html"
            } else if (resp.code === 401) {
                alert(resp.message)
                window.location.href = "index.html"
            } else {
                alert(resp.message)
            }
        },
        error: (xhr, status, err) => {
            alert(err.message)
        }
    })
}

const uid = getValueFromUrl("uid")
if (!uid) {
    alert("请选择要修改的用户")
    window.location.href = "index.html"
}

getUserInfo(uid)
// 监听提交事件
$(".update").click(function () {
    editUser(uid)
})